﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using OxyPlot;
using OxyPlot.Annotations;
using OxyPlot.Wpf;
using OxyPlot.Axes;
using OxyPlot.Series;


namespace 帆板仪表盘
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private SerialPort sp = new SerialPort();
        private StringBuilder builder = new StringBuilder();//避免在事件处理方法中反复的创建，定义到外面。
        private long received_count = 0;//接收计数
        //  private long send_count = 0;//发送计数
        private string singleData;
        string t = String.Empty;
        Mod m;
        List<Mod> list_Mod = new List<Mod>();
        int flag = 10;
        private MainViewModel viewModel1 = new MainViewModel();
        private MainViewModel viewModel2 = new MainViewModel();
        PlotModel model = new PlotModel();
       

        public MainWindow()
        {
            //DataContext = new List<DataPoint>{new DataPoint(1,2),new DataPoint(10,20),new DataPoint(15,4)};
            InitializeComponent();
            
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            RefreshCb_COM();
            // bt_Conn.IsEnabled= false;
            plot.DataContext = viewModel1;
            plot2.DataContext = viewModel2;
            tt_Help.ToolTip = ToolTip = "单击坐标可查看XY的值；\r\n滚轮按下框选可放大；\r\n滚轮在坐标处滑动可改变间距；\r\n右键可拖动图像；\r\n最好在关闭端口后进行操作\r\n数据格式：power:xxx角度:xxx(英文标点，无视\\r\\n)";
        }
        //刷新combox
        private void RefreshCb_COM()
        {
            viewModel1 = new MainViewModel();
            viewModel2= new MainViewModel();
            plot.DataContext = viewModel1;
            plot2.DataContext = viewModel2;
            sp.BaudRate = 115200;
            if (sp.IsOpen)
            {
                //打开时点击，则关闭串口
                sp.Close();
                bt_Conn.Content = "打开";
                cb_COM.IsEnabled = true;
            }
            sp.DataReceived -= comm_DataReceived;

            sp.DataReceived += comm_DataReceived;
            received_count = 0;
            labelGetCount.Text = "待测";
            cb_COM.IsEnabled = true;
            cb_COM.Items.Clear();
            foreach (string item in SerialPort.GetPortNames())
            {
                if (SerialFun.IsCommPortValid(item))
                {
                    cb_COM.Items.Add(item);
                }
                else
                {
                    cb_COM.Items.Add(item + "(Is Using)");
                }

            }

        }
        public void comm_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                int n = sp.BytesToRead;//先记录下来，避免某种原因，人为的原因，操作几次之间时间长，缓存不一致
                byte[] buf = new byte[n];//声明一个临时数组存储当前来的串口数据
                received_count += n;//增加接收计数
                sp.Read(buf, 0, n);//读取缓冲数据
                builder.Remove(0, builder.Length);///清除字符串构造器的内容

                var backgroundWorker = new BackgroundWorker();
                backgroundWorker.DoWork += (s, o) =>
                {
                    string temp;

                    temp = Encoding.Default.GetString(buf).Replace("\r", "").Replace("\n", "").Replace(" ", "");//出去字符串中所有的无用符号
                    //直接按ASCII规则转换成字符串
                    builder.Append(Encoding.Default.GetString(buf));
                    if (temp.Length >= 10)
                    {
                        /*处理数据*/
                         m = new Mod(temp,received_count);
                        viewModel1.Add(m.Count, m.Angle, "Angle", "");
                        viewModel2.Add(m.Count, m.Power, "Power", "");
                        lock (t) { t = temp; };


                    }
                    #region MyRegion

                    //丢弃来自串行驱动程序的接受缓冲区的数据
                    // sp.DiscardInBuffer();
                    //丢弃来自串行驱动程序的传输缓冲区的数据
                    //sp.DiscardOutBuffer();                

                    //追加的形式添加到文本框末端，并滚动到最后。
                    //this.tb_Rec.AppendText(builder.ToString());
                    //this.tb_Rec.AppendText("\r\n");

                    #endregion
                    //修改接收计数
                };

                backgroundWorker.RunWorkerCompleted += (s, args) =>
                {
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        labelGetCount.Text = received_count.ToString();
                        Angle.Text = m.Angle.ToString();
                        Power.Text = m.Power.ToString();
                        tb_State.Text = t;
                    }));
                };
                backgroundWorker.RunWorkerAsync();
            }
            catch (Exception)
            {
                MessageBox.Show("添大爷的程序竟然报Bug了！\r\nq请   刷   新  ！\r\n 或者重启本软件！", "凸(艹皿艹 )");
            }

        }

        private void bt_Conn_Click(object sender, RoutedEventArgs e)
        {
            if (sp.IsOpen)
            {
                //打开时点击，则关闭串口
                sp.Close();
                bt_Conn.Content = "打开";
                cb_COM.IsEnabled = true;
            }
            else
            {
                //关闭时点击，则设置好端口，波特率后打开
                bt_Conn.Content = "关闭";

                cb_COM.IsEnabled = false;
                sp.BaudRate = 115200;// int.Parse(comboBaudrate.Text);
                try
                {
                    sp.PortName = cb_COM.Text;
                    sp.BaudRate = 115200;
                    sp.Open();
                }
                catch (Exception ex)
                {
                    //捕获到异常信息，创建一个新的comm对象，之前的不能用了。
                    bt_Conn.Content = "连接";
                    sp = new SerialPort();
                    sp.BaudRate = 115200;
                    RefreshCb_COM();
                    //现实异常信息给客户。
                    // MessageBox.Show(ex.Message+"\r\n刷新！");
                }
            }
        }

        private void Image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            cb_COM.Items.Clear();
            RefreshCb_COM();
        }

        private void cb_COM_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            /*   if (cb_COM.Text == "" || cb_COM.Text.Length > 5)
               {
               }
               else
               {
                   bt_Conn.IsEnabled = true;//有效的COM才使能连接按钮
               }*/
        }
       
        public void createRD()
        {
            Random ra = new Random();

            for (int i = 0; i < 10; i++)
            {

                Mod md = new Mod((ra.NextDouble() * 5), ra.Next(2000), i);
                list_Mod.Add(md);
            }
        }

        private void createG_Click(object sender, RoutedEventArgs e)
        {
          
         //   flag +=1;

          //  viewModel.Add(flag, new Random ().NextDouble()*5);
            
           
          
        }
        //private void SetUpModel()
        //{
        //    model.LegendTitle = "Legend";
        //    model.LegendOrientation = LegendOrientation.Horizontal;
        //    model.LegendPlacement = LegendPlacement.Outside;
        //    model.LegendPosition = LegendPosition.TopRight;
        //    model.LegendBackground = OxyColor.FromAColor(200, OxyColors.White);
        //    model.LegendBorder = OxyColors.Black;

        //    var dateAxis = new OxyPlot.Axes.DateTimeAxis(AxisPosition.Bottom, "Date", "dd/MM/yy HH:mm") { MajorGridlineStyle = LineStyle.Solid, MinorGridlineStyle = LineStyle.Dot, IntervalLength = 80 };
        //    model.Axes.Add(dateAxis);
        //    var valueAxis = new OxyPlot.Axes.LinearAxis(AxisPosition.Left, 0) { MajorGridlineStyle = LineStyle.Solid, MinorGridlineStyle = LineStyle.Dot, Title = "Value" };
        //    model.Axes.Add(valueAxis);
        //}
     
        
    }
}
